/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.json.client;

import java.util.Collection;

import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONValue;

/**
 * The {@link Collection} json serializer.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 * 
 * @param <T> the type of item object
 */
public class CollectionSerializer<T> extends JsonValueSerializer<Collection<T>> {

  private static CollectionSerializer<Object> impl;

  /**
   * @return the instance of gereric {@link Collection} serializer
   */
  public static CollectionSerializer<Object> get() {
    if (impl == null) {
      impl = new CollectionSerializer<Object>(ObjectSerializer.get());
    }
    return impl;
  }

  /**
   * Gets an instance with the given item serializer.
   * 
   * @param itemSerializer the item serializer
   * @return the collection serializer of type
   */
  public static <T> CollectionSerializer<T> get(JsonValueSerializer<T> itemSerializer) {
    return new CollectionSerializer<T>(itemSerializer);
  }

  private JsonValueSerializer<T> itemSerializer;

  private CollectionSerializer(JsonValueSerializer<T> itemSerializer) {
    this.itemSerializer = itemSerializer;
  }

  @Override
  public JSONValue toJson(Collection<T> value) {
    JSONArray jsonArray = new JSONArray();
    int i = 0;
    for (T v : value) {
      jsonArray.set(i++, itemSerializer.toJson(v));
    }
    return jsonArray;
  }
}
